package com.mingliqiye.minecraft.enchantment.conflict.fabric.network;

import com.google.gson.Gson;
import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigManager;
import com.mingliqiye.minecraft.enchantment.conflict.common.MinecraftMod;
import com.mingliqiye.minecraft.enchantment.conflict.fabric.FabricMod;
import com.mojang.logging.LogUtils;
import io.netty.buffer.Unpooled;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger;

public class NetworkHandler {

    public static final ResourceLocation CONFIG_PACKET_ID = new ResourceLocation(MinecraftMod.MOD_ID, "config_packet");

    private static final Logger LOGGER = LogUtils.getLogger();

    public static void sendConfigToClient(ServerPlayer player) {
        var config = FabricMod.CONFIGMANAGER.getConfig();
        FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer());
        buf.writeUtf(ConfigManager.toyaml(config));
        ServerPlayNetworking.send(player, NetworkHandler.CONFIG_PACKET_ID, buf);
        LOGGER.info(
            "Send Player({}) Server {} config {}",
            player.getName().getString(),
            MinecraftMod.MOD_ID,
            ConfigManager.tojson(config)
        );
    }

    public static void sendConfigToAllClient() {
        FabricMod.SERVER.getPlayerList().getPlayers().forEach(NetworkHandler::sendConfigToClient);
    }

    public static void registerReceivers() {
        ClientPlayNetworking.registerGlobalReceiver(
            NetworkHandler.CONFIG_PACKET_ID,
            (client, handler, buf, responseSender) -> {
                var configData = ConfigManager.fromyaml(buf.readUtf());
                client.execute(() -> {
                    FabricMod.CONFIGMANAGER.setConfig(configData);
                    LOGGER.info("Load Server {} config {}", MinecraftMod.MOD_ID, ConfigManager.tojson(configData));
                });
            }
        );
    }
}
